<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/12/4
 * Time: 13:28
 */

namespace app\storage\model;


use think\Model;

class ContainerModel extends Model
{
    protected $table = 'iwh_containers';
    protected $pk = 'uuid';
    use \app\storage\util\Common;
    public function Storage()
    {
        return $this->belongsTo('StorageModel', 'storage_uuid', 'uuid')->bind('name');
    }

    public function ReelsModel(){
        return $this->belongsTo('ReelsModel','container_code','container_code');
    }

    public function getContainer($condition){
        $where = $condition['where'];
        $pageIndex = $condition['pageIndex'];
        $pageSize = $condition['pageSize'];
        $ret['total'] = $this->where($where)->count();
        $ret['row'] = $this->with('Storage')
            ->where($where)->order('container_code asc')
            ->page($pageIndex,$pageSize)
            ->select();
        return $ret;
    }

    public function queryContainer($condition){
        $where = $condition['where'];
        $pageIndex = $condition['pageIndex'];
        $pageSize = $condition['pageSize'];
        $havingArr = ['reel_count','type_count'];
        $having = $this->getHavingString($havingArr,$where);

        $reelModel = new ReelsModel();
        $ret['total'] = $reelModel->alias('r')
            ->join(['iwh_storage'=>'s'],'s.uuid = r.storage_uuid')
            ->field("count(distinct r.sub_materiel_id) as type_count,count(*) as reel_count,name")
            ->group('container_code')
            ->having($having)
            ->where($where)
            ->select()
            ->count();

        $ret['row'] = $reelModel->alias('r')
            ->join(['iwh_storage'=>'s'],'s.uuid = r.storage_uuid')
            ->field("container_code,seat_code,count(distinct r.sub_materiel_id) as type_count,count(*) as reel_count,name,status")
            ->order('container_code asc')
            ->group('container_code')
            ->page($pageIndex, $pageSize)
            ->having($having)
            ->where($where)
            ->select();

        return $ret;
    }

    public function queryContainerDetail($containerCode){
        $reelModel = new ReelsModel();
        $ret = $reelModel->field('reel_id,sub_materiel_id,seat_code,count,time')
            ->order('time desc')
            ->where('container_code',$containerCode)
            ->select();
        return $ret;
    }
    //添加一个以批次号前12位生成的容器
    public function addContainer($reelId){
        $where = [
            'uuid' => create_uuid(),
            'container_code' => substr($reelId,0,13),
            'type' => 'C',
            'status' => 0,
            'flag' => 0,
        ];
        $this->insert($where);
    }
}

